package com.graduation.log.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.graduation.client.StudentClint;
import com.graduation.common.result.R;
import com.graduation.common.utils.JwtHelper;
import com.graduation.log.service.InternshipGradeService;
import com.graduation.model.entity.InternshipGrade;
import com.graduation.model.entity.InternshipLog;
import com.graduation.model.vo.GradeQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tianwenle
 * @since 2022-11-18
 */
@RestController
@RequestMapping("/admin/log")
public class InternshipGradeController {

    @Autowired
    private InternshipGradeService internshipGradeService;
    @Autowired
    private StudentClint studentClint;


    @PutMapping("/grade/{logId}/{grade}")
    public R changeGrade(@PathVariable Long logId, @PathVariable String grade) {
        InternshipGrade internshipGrade = new InternshipGrade();
        internshipGrade.setLogId(logId);
        internshipGrade.setGrade(grade);
        QueryWrapper<InternshipGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("log_id", logId);
        InternshipGrade one = internshipGradeService.getOne(queryWrapper);
        if (one == null) {
            internshipGradeService.save(internshipGrade);
        } else {
            internshipGrade.setId(one.getId());
            internshipGradeService.updateById(internshipGrade);
        }
        return R.ok();
    }

    @GetMapping("/page/{pageSize}/{pageNum}")
    public R page(@PathVariable Integer pageSize, @PathVariable Integer pageNum, GradeQueryVo gradeQueryVo, HttpServletRequest request) throws UnsupportedEncodingException {
        String token = request.getHeader("X-Token");
        String loginNo = JwtHelper.getLoginNo(token);
        Long id = studentClint.getTeacherIdByUsername(loginNo);
        if (id != null) {
            gradeQueryVo.setTeacherId(id);
        }
        Map<String, Object> map = internshipGradeService.pageList(pageSize, pageNum, gradeQueryVo);
        return R.ok().data(map);
//        return R.ok();
    }

    // 获取指定实习日志的评分记录
    @GetMapping("/getGradeByLogId/{id}")
    public InternshipGrade getGradeByLogId(@PathVariable Long id) {
        QueryWrapper<InternshipGrade> wrapper = new QueryWrapper<>();
        wrapper.eq("log_id", id);
        return internshipGradeService.getOne(wrapper);
    }

}

